package threadPool;

import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 *  核心线程也允许销毁，allowsCoreThreadTimeOut就用来做这个事
 *  设置控制核心线程是否可能超时的策略，如果在保持活动时间内没有到达，则该策略将在新任务到达事根据需要被替换
 *  如果为false，则不会由于缺少传入任务而种植核心线程
 *  如果为true，则与应用与非核心线程的相同保持活动策略也适用于核心线程
 *  为避免连续更换线程，设置为true时保持活动时间必须大于0
 *  通常应该在线程池被激活之前调用此方法
 */
public class CoreThreadTimeOutTest {
    public static void main(String[] args) throws InterruptedException {
        // test0();
        test1();
    }
    // 开启核心线程池超时，保持与非核心线程活动策略一致
    public static void test1(){
        ThreadPoolExecutor pool = new ThreadPoolExecutor(4,5,
                5, TimeUnit.SECONDS,new LinkedBlockingDeque<>());
        pool.allowCoreThreadTimeOut(true);
        System.out.println("pool.getPoolSize() = " + pool.allowsCoreThreadTimeOut());
        Thread thread = new Thread(()->{
            System.out.println(Thread.currentThread().getName() + ".......");
        });
        pool.execute(thread);
        pool.execute(thread);
        pool.execute(thread);
        pool.execute(thread);
        try {
            Thread.sleep(8000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("pool.getPoolSize() = " + pool.getPoolSize());
    }
    // 默认核心线程池是无超时时间，常驻内存的
    public static void test0(){
        ThreadPoolExecutor pool = new ThreadPoolExecutor(4,5,
                5, TimeUnit.SECONDS,new LinkedBlockingDeque<>());
        pool.allowCoreThreadTimeOut(true);
        System.out.println("pool.getPoolSize() = " + pool.allowsCoreThreadTimeOut());
        Thread thread = new Thread(()->{
            System.out.println(Thread.currentThread().getName() + ".......");

        });
        pool.execute(thread);
        pool.execute(thread);
        pool.execute(thread);
        pool.execute(thread);
        try {
            Thread.sleep(8000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("pool.getPoolSize() = " + pool.getPoolSize());
    }
}
